<template>
  <div class="wms-item-brand-page art-full-height">
    <!-- 搜索栏 -->
    <WmsItemBrandSearch
      v-model:filter="searchFilter"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格工具栏 -->
      <ArtTableHeader
        v-model:columns="columnChecks"
        @refresh="refreshData"
        layout="refresh,size,fullscreen,columns,settings"
      >
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple>
            <ElIcon><Plus /></ElIcon>
            新增品牌
          </ElButton>
          <ElButton @click="handleBatchDelete" v-ripple>
            <ElIcon><Delete /></ElIcon>
            批量删除
          </ElButton>
          <ElButton @click="handleExport" v-ripple>
            <ElIcon><Download /></ElIcon>
            导出
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        rowKey="id"
        :loading="isLoading"
        :data="tableData"
        :columns="columns"
        :pagination="paginationState"
        @selection-change="handleSelectionChange"
        @pagination:size-change="onPageSizeChange"
        @pagination:current-change="onCurrentPageChange"
      >
        <!-- 自定义列插槽 -->
        <template #brandInfo="{ row }">
          <div class="brand-info">
            <div class="brand-name">{{ row.brandName }}</div>
            <div class="brand-code">{{ row.brandCode }}</div>
          </div>
        </template>

        <template #logo="{ row }">
          <ElImage
            v-if="row.logo"
            :src="row.logo"
            :preview-src-list="[row.logo]"
            style="width: 40px; height: 40px"
            fit="cover"
          />
          <span v-else class="text-placeholder">-</span>
        </template>

        <template #status="{ row }">
          <ElTag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "正常" : "停用" }}
          </ElTag>
        </template>

        <template #actions="{ row }">
          <ElButton type="primary" link @click="showDialog('edit', row)">
            <ElIcon><Edit /></ElIcon>
            编辑
          </ElButton>
          <ElButton type="danger" link @click="handleDelete(row)">
            <ElIcon><Delete /></ElIcon>
            删除
          </ElButton>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 品牌弹窗 -->
    <WmsItemBrandDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :brand-data="currentBrandData"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useTable } from "@/composables/useTable";
import { WmsItemBrandService } from "@/api/wms/basicApi";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Download } from "@element-plus/icons-vue";

// 导入子组件
import WmsItemBrandSearch from "./components/WmsItemBrandSearch.vue";
import WmsItemBrandDialog from "./components/WmsItemBrandDialog.vue";

defineOptions({ name: "WmsItemBrand" });

// 表格配置和数据处理逻辑
const {
  tableData,
  columns,
  columnChecks,
  isLoading,
  paginationState,
  searchFilter,
  onPageSizeChange,
  onCurrentPageChange,
  refreshData,
  handleSearch,
  handleReset,
} = useTable<WMS.Basic.ItemBrandInfo>({
  core: {
    apiFn: WmsItemBrandService.getItemBrandList,
    apiParams: {
      current: 1,
      size: 20,
    },
    columnsFactory: () => [
      {
        type: "selection",
        width: 50,
      },
      {
        prop: "brandInfo",
        label: "品牌信息",
        slot: "brandInfo",
        minWidth: 200,
        fixed: "left",
      },
      {
        prop: "logo",
        label: "品牌Logo",
        slot: "logo",
        width: 100,
        align: "center",
      },
      {
        prop: "status",
        label: "状态",
        slot: "status",
        width: 100,
        align: "center",
      },
      {
        prop: "createTime",
        label: "创建时间",
        width: 180,
        align: "center",
      },
      {
        prop: "remark",
        label: "备注",
        minWidth: 150,
        showOverflowTooltip: true,
      },
      {
        prop: "actions",
        label: "操作",
        slot: "actions",
        width: 150,
        fixed: "right",
        align: "center",
      },
    ],
  },
});

// 选中的行
const selectedRows = ref<WMS.Basic.ItemBrandInfo[]>([]);

// 弹窗状态管理
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const currentBrandData = ref<WMS.Basic.ItemBrandInfo | null>(null);

// 选择变化处理
const handleSelectionChange = (selection: WMS.Basic.ItemBrandInfo[]) => {
  selectedRows.value = selection;
};

// 显示弹窗
const showDialog = (type: "add" | "edit", data?: WMS.Basic.ItemBrandInfo) => {
  dialogType.value = type;
  currentBrandData.value = data ? { ...data } : null;
  dialogVisible.value = true;
};

// 弹窗提交处理
const handleDialogSubmit = async (data: WMS.Basic.ItemBrandInfo) => {
  try {
    if (dialogType.value === "add") {
      await WmsItemBrandService.createItemBrand(data);
      ElMessage.success("新增品牌成功");
    } else {
      await WmsItemBrandService.updateItemBrand(data.id, data);
      ElMessage.success("更新品牌成功");
    }
    dialogVisible.value = false;
    refreshData();
  } catch (error) {
    ElMessage.error(`${dialogType.value === "add" ? "新增" : "更新"}品牌失败`);
    console.error("Error submitting brand:", error);
  }
};

// 删除处理
const handleDelete = async (row: WMS.Basic.ItemBrandInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除品牌 "${row.brandName}" 吗？`,
      "删除确认",
      { type: "warning" },
    );

    await WmsItemBrandService.deleteItemBrand(row.id);
    ElMessage.success("删除品牌成功");
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除品牌失败");
      console.error("Error deleting brand:", error);
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的品牌");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个品牌吗？`,
      "批量删除确认",
      { type: "warning" },
    );

    const deletePromises = selectedRows.value.map((row) =>
      WmsItemBrandService.deleteItemBrand(row.id),
    );

    await Promise.all(deletePromises);
    ElMessage.success("批量删除成功");
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
      console.error("Error batch deleting brands:", error);
    }
  }
};

// 导出处理
const handleExport = () => {
  ElMessage.info("导出功能开发中");
};

// 页面初始化
onMounted(() => {
  refreshData();
});
</script>

<style lang="scss" scoped>
.wms-item-brand-page {
  .brand-info {
    .brand-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }

    .brand-code {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 2px;
    }
  }

  .text-placeholder {
    color: var(--el-text-color-placeholder);
  }
}
</style>
